package cn.lingyangwl.agile.pay.pay.model;

import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 支付回传参数
 *
 * @author shenguangyang
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class AliPassbackParams {
    /**
     * 交易类型
     */
    private String tradeType;

    /**
     * 如果不先进行base64对json字符串进行编码, 支付宝回调通知后, json解析会报错 <br/>
     * 支付宝要求目标字符串必须进行urlEncode编码, 所有最终的编码结果 = urlEncode(base64(targetStr))
     *
     * @return 被编码的字符串
     */
    public String encode() {
        String encode;
        try {
            encode = URLEncoder.encode(Base64.encode(JSON.toJSONString(this)), StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
        return encode;
    }

    public static AliPassbackParams decode(String encodeStr) {
        try {
            if (StringUtils.isEmpty(encodeStr)) {
                return null;
            }
            String decode = new String(Base64.decode(URLDecoder.decode(encodeStr, StandardCharsets.UTF_8.name())));
            return JSON.parseObject(decode, AliPassbackParams.class);
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }
}
